package com.spa.infrastructure.repository.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.spa.infrastructure.util.StringUtils;
import com.spa.infrastructure.repository.condition.AuthUserCondition;
import com.spa.infrastructure.repository.mapper.AuthUserMapper;
import com.spa.infrastructure.repository.po.AuthUserPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
@Slf4j
public class AuthUserRepositoryService extends MPJBaseServiceImpl<AuthUserMapper, AuthUserPO> {

    @Resource
    private AuthUserMapper authUserMapper;

    public Long addInfo(AuthUserPO po) {
        authUserMapper.insert(po);
        return po.getId();
    }

    public AuthUserPO getInfoById(Long id) {
        return getById(id);
    }

//    public AuthUserPO getInfo(AuthUserCondition condition) {
//        return getOne(wrapper(condition));
//    }

    public List<AuthUserPO> listInfo(AuthUserCondition condition) {
        return list(wrapper(condition));
    }

    public AuthUserPO listInfoOne(AuthUserCondition condition) {
        List<AuthUserPO> list = list(wrapper(condition));
        if(CollUtil.isNotEmpty(list)) return list.get(0);
        return null;
    }


    private LambdaQueryWrapper<AuthUserPO> wrapper(AuthUserCondition condition) {
        LambdaQueryWrapper<AuthUserPO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(StringUtils.isNotEmpty(condition.getOpenId()), AuthUserPO::getOpenId, condition.getOpenId());
        wrapper.eq(StringUtils.isNotNull(condition.getSource()), AuthUserPO::getSource, condition.getSource());
        wrapper.eq(ObjectUtil.isNotNull(condition.getUserId()),AuthUserPO::getUserId, condition.getUserId());
        wrapper.eq(ObjectUtil.isNotNull(condition.getUserSource()),AuthUserPO::getUserSource, condition.getUserSource());
        return wrapper;
    }

    /**
     * 清空用户第三方授权
     * @param condition
     * @return
     */
    public boolean clearAuth(AuthUserCondition condition){
        LambdaQueryWrapper<AuthUserPO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ObjectUtil.isNotNull(condition.getUserId()),AuthUserPO::getUserId, condition.getUserId());
        int res= authUserMapper.delete(wrapper);
        return res >= 0;
    }

}
